package cn.stronglink.assetmanage.business.search.presenter;

import android.content.Context;
import android.graphics.Bitmap;
import android.os.Handler;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.greenrobot.greendao.query.QueryBuilder;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import cn.stronglink.assetmanage.MyApplication;
import cn.stronglink.assetmanage.R;
import cn.stronglink.assetmanage.business.check.model.CheckDetailModel;
import cn.stronglink.assetmanage.business.check.view.detail.CheckDetailView;
import cn.stronglink.assetmanage.business.search.model.AssisChangeModel;
import cn.stronglink.assetmanage.business.search.view.AssisChange.AssisChangeView;
import cn.stronglink.assetmanage.business.search.view.AssisChange.IAssetDetailView;
import cn.stronglink.assetmanage.dao.DaoManager;
import cn.stronglink.assetmanage.dao.DepartmentDao;
import cn.stronglink.assetmanage.dao.ModelDao;
import cn.stronglink.assetmanage.dao.SearchAssetDao;
import cn.stronglink.assetmanage.dao.SyncTypesDao;
import cn.stronglink.assetmanage.dao.UserDao;
import cn.stronglink.assetmanage.entity.Asset;
import cn.stronglink.assetmanage.entity.Brand;
import cn.stronglink.assetmanage.entity.Department;
import cn.stronglink.assetmanage.entity.Model;
import cn.stronglink.assetmanage.entity.Result;
import cn.stronglink.assetmanage.entity.Room;
import cn.stronglink.assetmanage.entity.SearchAsset;
import cn.stronglink.assetmanage.entity.SyncTypes;
import cn.stronglink.assetmanage.entity.Type;
import cn.stronglink.assetmanage.entity.User;
import cn.stronglink.assetmanage.utils.ImageUtils;
import cn.stronglink.assetmanage.utils.ToastUtil;
import cn.stronglink.netrequest.business.search.SearchService;
import cn.stronglink.netrequest.exceptions.BusinessErrorException;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

/**
 * Created by zhengjinglan on 2018/6/20.
 */

public class AssisChangePresenter{

    private IAssetDetailView assetDetailView;
    private Context mContext;
    private SearchService searchService;
    private Gson gson;
    private Handler mHandler = new Handler();
    public AssisChangePresenter(Context context,IAssetDetailView detailView) {
        this.assetDetailView = detailView;
        this.mContext = context;
        searchService = new SearchService();
        gson = new Gson();
    }

    public List<Type> getTypeList() {
        List<Type> typeList = new ArrayList<>();
        try {
            Type type = new Type();
            type.setId_("");
            type.setName("请选择类型");
            typeList.add(type);

            List<Type> types = DaoManager.getDaoSession(mContext).getTypeDao().loadAll();
            if (types != null && types.size() > 0) {
                typeList.addAll(types);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return typeList;
    }

    public List<Brand> getBrandList() {
        List<Brand> brandList = new ArrayList<>();
        try {
            Brand brand = new Brand();
            brand.setId_("");
            brand.setName("请选择品牌");
            brandList.add(brand);
            List<Brand> brands = DaoManager.getDaoSession(mContext).getBrandDao().loadAll();
            if (brands != null && brands.size() > 0) {
                brandList.addAll(brands);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return brandList;
    }

    public List<Model> getModelList() {
        List<Model> modelList = new ArrayList<>();
        Model model = new Model();
        model.setBrandId_("");
        model.setTypeId_("");
        model.setId_("");
        model.setName("请选择型号");
        modelList.add(model);
        List<Model> models = DaoManager.getDaoSession(mContext).getModelDao().loadAll();
        if (models!=null&&models.size()>0){
            modelList.addAll(models);
        }
        return modelList;
    }

    public List<Room> getRoomList() {
        List<Room> roomList = new ArrayList<>();
        try {
            Room room = new Room();
            room.setId_("");
            room.setName("请选择地点");
            roomList.add(room);
            List<Room> rooms = DaoManager.getDaoSession(mContext).getRoomDao().loadAll();
            if (rooms != null && rooms.size() > 0) {
                roomList.addAll(rooms);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return roomList;
    }

    public void queryModelByBrandAndType() {
        try {
            List<Model> modelList = new ArrayList<>();
            Model model = new Model();
            model.setBrandId_("");
            model.setTypeId_("");
            model.setId_("");
            model.setName("请选择型号");
            modelList.add(model);
            List<Model> models = DaoManager.getDaoSession(mContext)
                    .getModelDao().queryBuilder().where(
                            ModelDao.Properties.BrandId_.eq(assetDetailView.getBrandValue()),
                            ModelDao.Properties.TypeId_.eq(assetDetailView.getTypeValue())).list();
            if (models != null) {
                modelList.addAll(models);
            }
            assetDetailView.onQueryModelListSuccess(modelList);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    // 获取资产详情
    public SearchAsset getAssetDetail(String id) {
        SearchAsset searchAsset = null;
        try {
            searchAsset = DaoManager.getDaoSession(mContext)
                    .getSearchAssetDao().queryBuilder().where(SearchAssetDao.Properties.Id_.eq(id)).unique();
        }catch (Exception e){
            e.printStackTrace();
        }
       return searchAsset;
    }

    public Bitmap getBitmap(String url) {
        Bitmap bitmap=null;
        try {
          bitmap = ImageUtils.getNativeImage(url);
        }catch (Exception e){
            e.printStackTrace();
        }
      return bitmap;
    }

    public List<User> getUserList() {
        List<User> userList = new ArrayList<>();
        try {

            User user = new User();
            user.setId_("");
            user.setName("请选择使用人");
            userList.add(user);
            List<User> users = DaoManager.getDaoSession(mContext).getUserDao().loadAll();
            if (users != null) {
                userList.addAll(users);
            }

        }catch (Exception e){
            e.printStackTrace();
        }
        return userList;
    }

    public String getManageName(String id) {
        String name = "";
        try {
            Department department = DaoManager.getDaoSession(mContext).getDepartmentDao()
                    .queryBuilder().where(DepartmentDao.Properties.Id_.eq(id)).unique();
            if (department != null) {
                name = department.getName();
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return name;
    }

    public void save(SearchAsset searchAsset){
        try {
            if (searchAsset.getAssetNo() == null || searchAsset.getAssetNo().isEmpty()) {
                ToastUtil.toastShort("资产编号不能为空");
                return;
            }
            if (searchAsset.getSerialNo() == null || searchAsset.getSerialNo().isEmpty()) {
                ToastUtil.toastShort("SN号不能为空");
                return;
            }
            if (assetDetailView.getCurrentBitmap() != null) {
                if (searchAsset.getPictureUri() != null && !searchAsset.getPictureUri().isEmpty()) {
                    ImageUtils.deleteImage(searchAsset.getPictureUri());
                }
                String url = ImageUtils.saveImageToLocal(assetDetailView.getCurrentBitmap());
                searchAsset.setPictureUri(url);
            }
            searchAsset.setId(Long.valueOf(searchAsset.getId_()));
            if (searchAsset.getManageBranchId_() != null && !searchAsset.getManageBranchId_().isEmpty()) {
                searchAsset.setManageBranchId(Long.valueOf(searchAsset.getManageBranchId_()));
            }
            if (searchAsset.getRoomId_() != null && !searchAsset.getRoomId_().isEmpty()) {
                searchAsset.setRoomId(Long.valueOf(searchAsset.getRoomId_()));
            }
            if (searchAsset.getTypeId_() != null && !searchAsset.getTypeId_().isEmpty()) {
                searchAsset.setTypeId(Long.valueOf(searchAsset.getTypeId_()));
            }
            if (searchAsset.getBrandId_() != null && !searchAsset.getBrandId_().isEmpty()) {
                searchAsset.setBrandId(Long.valueOf(searchAsset.getBrandId_()));
            }
            if (searchAsset.getModelId_() != null && !searchAsset.getModelId_().isEmpty()) {
                searchAsset.setModelId(Long.valueOf(searchAsset.getModelId_()));
            }
            if (searchAsset.getDatacenterId_() != null && !searchAsset.getDatacenterId_().isEmpty()) {
                searchAsset.setDatacenterId(Long.valueOf(searchAsset.getDatacenterId_()));
            }
            if (searchAsset.getUseBranchId_() != null && !searchAsset.getUseBranchId_().isEmpty()) {
                searchAsset.setUseBranchId(Long.valueOf(searchAsset.getUseBranchId_()));
            }
            String time = new SimpleDateFormat("yyyy-MM-dd hh:MM:ss").format(new Date());
            searchAsset.setUpdateTime(time);
            searchAsset.setUpdateBy(Long.valueOf(User.getInstance().getId_()));
            // 1.自动 2.离线
            SyncTypes syncType = DaoManager.getDaoSession(mContext).getSyncTypesDao()
                    .queryBuilder().where(SyncTypesDao.Properties.IsSelected.eq(true)).unique();
            int tp = 0;
            if (syncType != null) {
                tp = syncType.getSyscTs();
            }

            if (tp == 1) {
                if (searchAsset.getPictureUri() != null && !searchAsset.getPictureUri().isEmpty()) {
                    String base64 = ImageUtils.imageToBase64(searchAsset.getPictureUri());
                    if (base64 != null && !base64.isEmpty()) {
                        searchAsset.setImgPath(base64);
                    }
                }
                saveToWeb(searchAsset);
            } else {
                saveToLocal(searchAsset);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    private void saveToWeb(final SearchAsset searchAsset){
        assetDetailView.showProgress("正在上传资产数据");
        final String json = gson.toJson(searchAsset);
        try {
            searchService.updateAssetData(json, new Callback() {
                @Override
                public void onFailure(Call call, final IOException e) {
                    mHandler.post(new Runnable() {
                        @Override
                        public void run() {
                            assetDetailView.onUploadFail(e,searchAsset);
                            assetDetailView.hideProgress();
//                            saveToLocal(searchAsset);
                        }
                    });
                }
                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    final String json = response.body().string();
                    mHandler.post(new Runnable() {
                        @Override
                        public void run() {
                            Result<String> result = null;
                            result = gson.fromJson(json,new TypeToken<Result<String>>(){}.getType());
                            if (result != null && result.getHttpCode() == HttpURLConnection.HTTP_OK) {
                                DaoManager.getDaoSession(mContext).getSearchAssetDao()
                                        .deleteByKey(searchAsset.getSearch_asset_id());
                                if (searchAsset.getPictureUri()!=null&&!searchAsset.getPictureUri().isEmpty()){
                                    ImageUtils.deleteImage(searchAsset.getPictureUri());
                                }
                                assetDetailView.hideProgress();
                                assetDetailView.onUploadSuccess(searchAsset);
                            }else{
                                assetDetailView.onUploadFail(new BusinessErrorException(result.getMsg()),searchAsset);
//                                saveToLocal(searchAsset);
                                assetDetailView.hideProgress();
                            }
                        }
                    });
                }
            });
        } catch (final Exception e) {
            e.printStackTrace();
            mHandler.post(new Runnable() {
                @Override
                public void run() {
                    assetDetailView.onUploadFail(e,searchAsset);
                    assetDetailView.hideProgress();
                }
            });
//            saveToLocal(searchAsset);
        }
    }

    public void saveToLocal(SearchAsset searchAsset){
        try {
            DaoManager.getDaoSession(mContext).getSearchAssetDao().update(searchAsset);
            assetDetailView.onSaveLocalSuccess(searchAsset);
        }catch (Exception e){
            assetDetailView.onSaveLocalFail(new BusinessErrorException("保存本地数据失败"));
        }

    }
    public String getUserName(String endUser) {
        String userName="";
        User user = DaoManager.getDaoSession(mContext).getUserDao().queryBuilder()
                .where(UserDao.Properties.Id_.eq(endUser)).unique();
        if (user!=null){
            userName = user.getName();
        }
        return userName;
    }
}
